<template>
  <div>
<!--    <el-card>-->
      <el-form inline>
        <el-form-item label="用户名：">
          <el-input
              placeholder="请输入用户名"
              v-model="username"
              clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              @click="
                            getTableData({ page: 1, limit: pageSize, username })
                        "
          >搜索</el-button
          >
        </el-form-item>
      </el-form>
<!--    </el-card>-->
<!--    <el-card style="margin-top: 10px">-->
      <div>
        <el-button type="primary" @click="clickBtn">添加用户</el-button>
        <el-popconfirm title="亲爱的，确认批量删除吗？" @confirm="deleteSome">
          <template #reference>
            <el-button type="danger" :disabled="selectedSomeUsers.length<=0">批量删除</el-button>
          </template>
        </el-popconfirm>
      </div>
      <el-table
          :data="tableData"
          border
          style="width: 100%; margin: 10px 0"
          v-loading="loading"
          height="300px"
          @selection-change="handleSelectionChange"
      >
        <el-table-column align="center" type="selection" width="55" />
        <el-table-column align="center" label="#" width="55">
          <template #default="scope">
                        <span>{{
                            (currentPage - 1) * pageSize + scope.$index + 1
                          }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="id" label="ID" />
        <el-table-column align="center" prop="name" label="用户名字" />
        <el-table-column
            align="center"
            prop="username"
            label="用户名称"
        />
        <el-table-column
            label="用户角色"
            width="300px"
        >
          <template #default="scope">
            <el-tag
                v-for="(item,index) in scope.row.roleName ? scope.row.roleName.split(',') : []"
                :key="index"
                effect="light"
                :type="item.length > 4? 'primary':'success'"
                style="margin-right: 4px;"
            >
              {{ item }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
            align="center"
            prop="createTime"
            label="创建时间"
            show-overflow-tooltip
        />
        <el-table-column
            align="center"
            prop="updateTime"
            label="更新时间"
            show-overflow-tooltip
        />
        <el-table-column align="center" label="操作" width="250px">
          <template #default="scope">
            <el-button
                size="small"
                type="primary"
                @click="handleRoleAuth(scope.row)"
            >
              授权角色
            </el-button>
            <el-button
                size="small"
                type="primary"
                @click="handleModify(scope.$index, scope.row)"
            >
              编辑
            </el-button>
            <el-popconfirm title="亲爱的，确认要删除我吗？" @confirm="handleDelete(scope.row)">
              <template #reference>
                <el-button
                    size="small"
                    type="danger"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>

          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[2, 3, 4]"
          :small="small"
          layout="prev, pager, next, jumper, sizes, total"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
<!--    </el-card>-->
    <!-- 新增用户 -->
    <el-drawer v-model="drawerFlag" :title="ADD_OR_MODIFY_FLAG ? '添加用户信息':'修改用户信息'" direction="rtl">
      <el-form
          :model="addForm"
          ref="formRef"
          :rules="rules"
          label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="addForm.username"
              placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="昵 称" prop="name">
          <el-input
              v-model="addForm.name"
              placeholder="请输入昵称"
          ></el-input>
        </el-form-item>
        <!-- 密码的item添加的时候会显示，修改的时候不会显示 -->
        <!-- ADD_OR_MODIFY_FLAG 来判断-->
        <el-form-item label="密 码" prop="password" v-if="ADD_OR_MODIFY_FLAG">
          <el-input
              v-model="addForm.password"
              placeholder="请输入密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="btn">
        <el-button type="primary" @click="addUser" v-if="ADD_OR_MODIFY_FLAG">新 增</el-button>
        <el-button type="primary" @click="updateUser" v-else>修 改</el-button>
      </div>
    </el-drawer>

    <!--  角色授权的页面  -->
    <el-drawer v-model="IS_SHOW_ROLE_AUTH_FLAG" title="角色授权">
      <p class="role_auth_title">角色授权：将该用户分配下列的角色</p>
      <span class="role_auth_name">{{ name }}</span><br />
      <div class="check_box_container" v-loading="roleRoading">
        <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
        >
          全部😀
        </el-checkbox>
        <el-checkbox-group
            v-model="ownedRoles"
            @change="handleCheckedRolesChange"
        >
          <el-checkbox v-for="role in allRoleList" :key="role.id" :value="role">
            {{ role.roleName }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <el-button type="primary" @click="handleAddRole">授 权</el-button>
    </el-drawer>
  </div>
</template>

<script>
import { defineComponent, onMounted, ref, reactive } from "vue"
import { getAllSystemUsers, addSystemUsers, updateSystemUsers, getAllRoleListAndOwnedRoles, addRoles, deleteTheUser, deleteSomeUsers } from "@/api/auth/user/index"
import { ElMessage } from "element-plus"

export default defineComponent({
  name: "user",
  setup() {
    const tableData = ref([])
    let total = ref()
    let currentPage = ref(1)
    let pageSize = ref(3)
    const loading = ref(false)
    let username = ref("")
    let drawerFlag = ref(false)
    let ADD_OR_MODIFY_FLAG = ref(true)

    onMounted(() => {
      getTableData({
        page: currentPage.value,
        limit: pageSize.value,
      })
    })

    // 查询用户列表的数据
    const getTableData = async (data) => {
      loading.value = true
      let res = await getAllSystemUsers(data)
      loading.value = false
      tableData.value = res.data.records
      total.value = res.data.total
      currentPage.value = res.data.current
      pageSize.value = res.data.size
    }

    // 分页
    const handleCurrentChange = () => {
      getTableData({
        page: currentPage.value,
        limit: pageSize.value,
        username: username.value,
      })
    }

    const handleSizeChange = () => {
      getTableData({
        page: 1,
        limit: pageSize.value,
        username: username.value,
      })
    }

    const addForm = reactive({
      username: "",
      name: "",
      password: "",
    })
    let formRef = ref()

    const addUser = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          addSystemUsers(addForm).then((res) => {
            if (res.code === 200) {
              ElMessage({
                message: "添加成功",
                type: "success",
              })
              getTableData({
                page: 1,
                limit: pageSize.value,
              })
            } else {
              ElMessage.error("添加失败，请联系管理员")
            }
            /**
             * 这里我出现一个问题，prop加错了位置
             *
             */
            formRef.value.resetFields()
            // 关闭抽屉
            drawerFlag.value = false
          })
        }
      })
    }

    const rules = reactive({
      name: [
        {
          required: true,
          message: "小可爱😀必填项哦",
          trigger: "blur",
        },
        {
          min: 5,
          max: 10,
          message: "长度为5~10之间",
          trigger: "blur",
        },
      ],
      username: [
        {
          required: true,
          message: "小可爱😀必填项哦",
          trigger: "blur",
        },
        {
          min: 5,
          max: 10,
          message: "长度为5~10之间",
          trigger: "blur",
        },
      ],
      password: [
        {
          required: true,
          message: "小可爱😀必填项哦",
          trigger: "blur",
        },
        {
          min: 5,
          max: 10,
          message: "长度为5~10之间",
          trigger: "blur",
        },
        {
          validator: (rule, value, callback) => {
            if (/^\d+$/.test(value)) {
              callback()
            } else {
              callback("密码只能为数字，否则不能提交哦啊")
            }
          },
        },
      ],
    })

    const clickBtn = () => {
      drawerFlag.value = true //打开抽屉

      ADD_OR_MODIFY_FLAG.value = true

      formRef.value?.resetFields() //重置表单 第一次不执行
    }

    // 修改
    const handleModify = (index, row) => {
      drawerFlag.value = true //打开抽屉
      ADD_OR_MODIFY_FLAG.value = false

      addForm.username = row.username// 赋值回显
      addForm.name = row.name// 赋值回显
      addForm.id = row.id
    }

    const updateUser = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          updateSystemUsers({ username: addForm.username, name: addForm.name, id: addForm.id }).then((res) => {
            if (res.code === 200) {
              ElMessage({
                message: "修改成功",
                type: "success",
              })
              getTableData({
                page: currentPage.value,
                limit: pageSize.value,
              })
            } else {
              ElMessage.error("修改失败，请联系管理员")
            }
            /**
             * 这里我出现一个问题，prop加错了位置
             *
             */
            formRef.value.resetFields()
            // 关闭抽屉
            drawerFlag.value = false
          })
        }
      })
    }

    let IS_SHOW_ROLE_AUTH_FLAG = ref(false)// 角色授权页面

    let name = ref('')

    // 全部可选角色
    const allRoleList = ref([])
    // 已拥有的角色
    const ownedRoles = ref([])
    let roleRoading = ref(false)
    let roleId = ref()

    const handleRoleAuth = (rowInfo) => {
      IS_SHOW_ROLE_AUTH_FLAG.value = true
      roleRoading.value = true
      name.value = rowInfo.name // 显示用户名
      roleId.value = rowInfo.id

      getAllRoleListAndOwnedRoles(rowInfo.id).then((res) => {
        if(res.code === 200) {
          allRoleList.value = res.data.allRolesList
          ownedRoles.value = res.data.assignRoles
          handleCheckedRolesChange(ownedRoles.value) // 控制全选按钮的value值与是否为不确定的状态
        }
        roleRoading.value = false
      }).catch(() => {
        roleRoading.value = false
      })
    }

    let checkAll = ref(false)
    let isIndeterminate = ref(false)

    const handleCheckedRolesChange = (value) => {
      const checkedCount = value.length
      checkAll.value = checkedCount === allRoleList.value.length
      isIndeterminate.value = checkedCount > 0 && checkedCount < allRoleList.value.length
    }

    const handleCheckAllChange = (val) => {
      ownedRoles.value = val ? allRoleList.value : []
      isIndeterminate.value = false
    }

    const handleAddRole = () => {
      // console.log(ownedRoles.value)
      // console.log(roleId.value)
      addRoles({
        userId: roleId.value,
        roleIdList: ownedRoles.value.map(i => i.id)
      }).then((res) => {
        if(res.code === 200) {
          ElMessage({
            message: "授权角色成功",
            type: "success"
          })
        } else {
          ElMessage.error("授权角色失败")
        }
        IS_SHOW_ROLE_AUTH_FLAG.value = false
        // 获取新的列表数据
        getTableData({
          page: currentPage.value,
          limit: pageSize.value,
          username: username.value
        })
      }).catch(() => {
        IS_SHOW_ROLE_AUTH_FLAG.value = false
      })
    }

    // 删除用户
    const handleDelete = (rowInfo) => {
      deleteTheUser(rowInfo.id).then((res) => {
        if(res.code === 200) {
          ElMessage({
            message: "该用户删除成功",
            type: "success"
          })
        }
        let page
        // 查询第几页的判断
        if(tableData.value.length > 1) {
          page = currentPage.value
        } else if(currentPage.value === 1){
          page = 1
        } else {
          page = currentPage.value - 1
        }
        getTableData({
          page,
          limit: pageSize.value,
          username: username.value
        })
      })
    }

    const selectedSomeUsers = ref([]) // 左侧已勾选的用户数据

    const deleteSome = () => {
      // console.log(selectedSomeUsers.value,'======>selectedSomeUsers.value')
      deleteSomeUsers(selectedSomeUsers.value).then((res) => {
        if(res.code === 200) {
          ElMessage({
            message: "批量删除成功",
            type: "success"
          })
        }
        // 删除后查询
        let page
        // 查询第几页的判断
        if(tableData.value.length > selectedSomeUsers.value.length) {
          page = currentPage.value
        } else if(currentPage.value === 1){
          page = 1
        } else {
          page = currentPage.value - 1
        }
        getTableData({
          page,
          limit: pageSize.value,
          username: username.value
        })
      })
    }

    const handleSelectionChange = (data) => {
      // data为选择的数据
      selectedSomeUsers.value = data.map(i => i.id)
    }


    return {
      tableData,
      total,
      currentPage,
      pageSize,
      handleCurrentChange,
      handleSizeChange,
      loading,
      username,
      getTableData,
      drawerFlag,
      addForm,
      addUser,
      formRef,
      rules,
      clickBtn,
      handleModify,
      ADD_OR_MODIFY_FLAG,
      updateUser,
      IS_SHOW_ROLE_AUTH_FLAG,
      handleRoleAuth,
      name,
      checkAll,
      allRoleList,
      ownedRoles,
      handleCheckedRolesChange,
      isIndeterminate,
      handleCheckAllChange,
      roleRoading,
      handleAddRole,
      handleDelete,
      deleteTheUser,
      deleteSome,
      handleSelectionChange,
      selectedSomeUsers
    }
  },
})
</script>

<style scoped lang="scss">
.btn {
  display: flex;
  justify-content: right;
}
.role_auth_title {
  color: lightgray;
}
.role_auth_name {
  display: inline-block;
  margin: 30px 0;
  color: lightseagreen;
  font-size: 30px;
  font-weight: bold;
}
.check_box_container {
  padding: 20px;
  border: 1px solid lightseagreen;
  border-radius: 10px;
}
</style>
